//
//  RentDetailViewController.m
//  ZhuanZuBao
//
//  Created by bchy on 2020/8/28.
//  Copyright © 2020 戴伟. All rights reserved.
//

#import "RentDetailViewController.h"
#import "RentModel.h"
#import "SDCycleScrollView.h"
#import "TTGTextTagCollectionView.h"
#import "ImageBroswerViewController.h"
#import "RentMapViewController.h"
#import "CustomAnnotationView.h"
#import "ShareViewController.h"

@interface RentDetailViewController ()<MAMapViewDelegate, UIScrollViewDelegate, SDCycleScrollViewDelegate>

@property (nonatomic, copy) NSString *rentId;

@property (nonatomic, strong) RentModel *rent;

@property (nonatomic, strong) UILabel *indexLabel;

@property (strong, nonatomic) IBOutlet UIView *detailView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *floorLabel;
@property (weak, nonatomic) IBOutlet UILabel *areaLabel;
@property (weak, nonatomic) IBOutlet UILabel *houseTypeLabel;
@property (weak, nonatomic) IBOutlet UILabel *detailLabel;

@property (nonatomic, strong) TTGTextTagCollectionView *tagView;
@property (weak, nonatomic) IBOutlet UIView *tagBgView;
@property (weak, nonatomic) IBOutlet UIView *mapBgView;
@property (weak, nonatomic) IBOutlet UIButton *collectBtn;
@property (weak, nonatomic) IBOutlet UIButton *shareBtn;
@property (weak, nonatomic) IBOutlet UIView *navView;

@end

@implementation RentDetailViewController

- (BOOL)fd_prefersNavigationBarHidden{
    return YES;
}


-(instancetype)initWithRentId:(NSString *)rentId{
    if (self = [super init]) {
        _rentId = rentId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"转租详情";
    
    [_navView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(SafeAreaTopHeight);
    }];
    _shareBtn.tintColor = BLACKTEXTCOLOR;
    [_shareBtn setImage:[[UIImage imageNamed:@"share"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    [MBProgressHUD showMessag:@"" toView:self.view];
    [self getData];
    
}
-(void)getData{
    NSDictionary *dict = @{
        @"id": _rentId,
        @"uid": [User isLogined]? [User sharedUser].userId:@""
    };
    [NetWork sendGetUrl:@"fy/fy_dtl.php" withParams:dict success:^(id responseBody) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"%@", responseBody);
        self.rent = [RentModel mj_objectWithKeyValues:responseBody];
        
        [self setupUI];
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

-(void)setupUI{
    if (_rent.collected) {
        [_collectBtn setTitle:@" 已收藏" forState:UIControlStateNormal];
    }else{
        [_collectBtn setTitle:@" 收藏" forState:UIControlStateNormal];
    }
    self.view.backgroundColor = [UIColor whiteColor];
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_SCREEN_WIDTH, DEVICE_SCREEN_HEIGHT-44-SafeAreaBottomMarginHeight)];
    if (@available(iOS 11.0, *)) {
           scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
       self.automaticallyAdjustsScrollViewInsets = NO;
    }

    scrollView.delegate = self;
    scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:scrollView];
//    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.mas_offset(0);
//        make.top
//        make.height.mas_equalTo(DEVICE_SCREEN_HEIGHT-SafeAreaTopHeight-SafeAreaBottomHeight-44);
//    }];
    
    UIView *containerView = [UIView new];
    [scrollView addSubview:containerView];
    [containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(scrollView);
        make.width.equalTo(scrollView);
    }];
    
    [containerView addSubview:_detailView];
    [_detailView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_offset(0);
    }];
    
    [containerView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.detailView.mas_bottom).mas_offset(40);
    }];
    
    SDCycleScrollView *bannerView = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_SCREEN_WIDTH, DEVICE_SCREEN_WIDTH)];
    bannerView.backgroundColor = BGCOLOR;
    bannerView.showPageControl = NO;
    bannerView.delegate = self;
    bannerView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    [scrollView addSubview:bannerView];
    
    NSMutableArray *arr = [NSMutableArray array];
    if (_rent.images && _rent.images.length > 0) {
        [arr addObjectsFromArray:[_rent.images componentsSeparatedByString:@","]];
    }
    if (_rent.cover && _rent.cover.length > 0) {
        [arr insertObject:_rent.cover atIndex:0];
    }
    bannerView.imageURLStringsGroup = arr;
    
    _indexLabel = [UILabel new];
    _indexLabel.textColor = [UIColor whiteColor];
    _indexLabel.textAlignment = NSTextAlignmentCenter;
    _indexLabel.text = [NSString stringWithFormat:@"图片1/%ld", (unsigned long)arr.count];
    _indexLabel.font = [UIFont systemFontOfSize:12];
    _indexLabel.layer.masksToBounds = YES;
    _indexLabel.layer.cornerRadius = 12;
    [scrollView addSubview:_indexLabel];
    _indexLabel.backgroundColor = BLACKTEXTCOLOR;
    [_indexLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(bannerView).mas_offset(-12);
        make.centerX.equalTo(bannerView);
        make.width.mas_equalTo(64);
        make.height.mas_equalTo(24);
    }];
    
    _titleLabel.text = _rent.title;
    CGFloat titleHeight = [_rent.title sizeWithMyFont:[UIFont systemFontOfSize:17 weight:UIFontWeightMedium] constrainedToSize:CGSizeMake(DEVICE_SCREEN_WIDTH-24, MAXFLOAT)].height;
    _priceLabel.text = [NSString stringWithFormat:@"%@元/月", _rent.price];
    _houseTypeLabel.text = _rent.houseType;
    _floorLabel.text = _rent.floor;
    _areaLabel.text = [NSString stringWithFormat:@"%ld㎡", _rent.area];
    
    
    
    self.tagView = [[TTGTextTagCollectionView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_SCREEN_WIDTH-24, 50)];
    [_tagBgView addSubview:self.tagView];
    _tagBgView.backgroundColor = [UIColor whiteColor];
    _tagView.enableTagSelection = NO;
    TTGTextTagConfig *config = [[TTGTextTagConfig alloc] init];
    config.textColor = THEMECOLOR;
    config.shadowOpacity = 0;
    config.cornerRadius = 0;
    config.selectedCornerRadius = 0;
    config.borderColor = THEMECOLOR;
    config.borderWidth = 0.8;
    config.extraSpace = CGSizeMake(24, 10);
    config.backgroundColor = [UIColor whiteColor];
    config.textFont = [UIFont systemFontOfSize:13];
    config.selectedTextColor = [UIColor whiteColor];
    config.selectedBackgroundColor = [UIColor whiteColor];
    [self.tagView addTags:[_rent.tags componentsSeparatedByString:@","] withConfig:config];
    
    self.tagView.frame = CGRectMake(0, 0, DEVICE_SCREEN_WIDTH-24, self.tagView.contentSize.height);
    [_tagBgView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.tagView.contentSize.height);
    }];
    
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.lineSpacing = 8;
    NSDictionary *dict = @{
                           NSFontAttributeName: [UIFont systemFontOfSize:15],
                           NSParagraphStyleAttributeName:paragraphStyle
                           };
    NSAttributedString *str1 = [[NSAttributedString alloc] initWithString:_rent.content attributes:dict];
    _detailLabel.attributedText = str1;
    
    CGFloat contentHeight  = [_rent.content boundingRectWithSize:CGSizeMake(DEVICE_SCREEN_WIDTH-24, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size.height;
    
    [_detailView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(titleHeight+contentHeight+_tagView.contentSize.height+DEVICE_SCREEN_WIDTH+400);
    }];
    //添加地图
    MAMapView *mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_SCREEN_WIDTH, 128)];
    [self.mapBgView addSubview:mapView];
    mapView.delegate = self;
    
    mapView.showsUserLocation = YES;
    mapView.userTrackingMode = MAUserTrackingModeFollow;
    
    if (_rent.lat && _rent.lat.length > 0) {
        MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
        pointAnnotation.coordinate = CLLocationCoordinate2DMake([_rent.lat floatValue], [_rent.lon floatValue]);
        pointAnnotation.title = [NSString stringWithFormat:@"%@ %@", _rent.district, _rent.community];
        pointAnnotation.subtitle = _rent.metro;

        [mapView addAnnotation:pointAnnotation];
        [mapView setCenterCoordinate:pointAnnotation.coordinate animated:YES];
    }
    //在地图上面加一个按钮，点击进入大地图
    UIButton *mapBtn = [[UIButton alloc] initWithFrame:mapView.bounds];
    [mapBtn addTarget:self action:@selector(mapTaped) forControlEvents:UIControlEventTouchUpInside];
    [self.mapBgView addSubview:mapBtn];
    //加两个按钮
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(4, SafeAreaTopHeight-44, 44, 44)];
    [backBtn setImage:[[UIImage imageNamed:@"return"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    backBtn.tintColor = [UIColor whiteColor];
    [scrollView addSubview:backBtn];
    [backBtn addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *shareBtn = [[UIButton alloc] initWithFrame:CGRectMake(DEVICE_SCREEN_WIDTH-44-4, SafeAreaTopHeight-44, 44, 44)];
    [shareBtn setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    [scrollView addSubview:shareBtn];
    [shareBtn addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view bringSubviewToFront:_navView];
    _navView.alpha = 0;
}
- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 打电话
- (IBAction)call:(id)sender {
    NSMutableString* str=[[NSMutableString alloc] initWithFormat:@"tel:%@", _rent.phone];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
#pragma mark - 收藏

- (IBAction)collect:(id)sender {
    if ([User isGuest]) {
        LoginViewController *vc = [LoginViewController new];
        BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:vc];
        [self presentViewController:vc animated:YES completion:nil];
        return;
    }

    NSDictionary *dict = @{
        @"uid": [User sharedUser].userId,
        @"token": [User sharedUser].token,
        @"id": _rentId
    };
    [MBProgressHUD showMessag:@"" toView:self.view];
    [NetWork sendGetUrl:@"fy/fy_fav.php" withParams:dict success:^(id responseBody) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        self.rent.collected = !self.rent.collected;
        if (self.rent.collected) {
            [self.collectBtn setTitle:@" 已收藏" forState:UIControlStateNormal];
            [MBProgressHUD showSuccess:@"已收藏" toView:nil];
        }else{
            [self.collectBtn setTitle:@" 收藏" forState:UIControlStateNormal];
            [MBProgressHUD showSuccess:@"取消收藏" toView:nil];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (void)mapViewRequireLocationAuth:(CLLocationManager *)locationManager
{
    [locationManager requestAlwaysAuthorization];
}

- (IBAction)share:(id)sender {
    ShareViewController *vc = [ShareViewController new];
    vc.link = @"http://share.cdlife.vip/zzb/index.html";
    vc.shareTitle = @"转租宝";
    vc.shareDesc = @"转租宝APP-最新版下载链接，欢迎下载，海量房源等你来看！";
    vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:vc animated:NO completion:nil];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY < 0) {
        _navView.alpha = 0;
    }else if (offsetY > SafeAreaTopHeight){
        _navView.alpha = 1;
    }
}

/** 点击图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    NSMutableArray *arr = [NSMutableArray arrayWithArray:[_rent.images componentsSeparatedByString:@","]];
    if (_rent.cover && _rent.cover.length > 0) {
        [arr insertObject:_rent.cover atIndex:0];
    }
    
    ImageBroswerViewController *vc = [[ImageBroswerViewController alloc] initWithImageArr:arr];
    vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - 图片滚动回调
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index{
    NSMutableArray *arr = [NSMutableArray arrayWithArray:[_rent.images componentsSeparatedByString:@","]];
    if (_rent.cover && _rent.cover.length > 0) {
        [arr insertObject:_rent.cover atIndex:0];
    }
    _indexLabel.text = [NSString stringWithFormat:@"图片%ld/%ld",index+1, arr.count];
}

#pragma mark - 点击进入大地图
-(void)mapTaped{
    RentMapViewController *vc = [[RentMapViewController alloc] initWithLat:[_rent.lat floatValue] lon:[_rent.lon floatValue]];
    vc.community = [NSString stringWithFormat:@"%@ %@", _rent.district, _rent.community];
    vc.metro = _rent.metro;
    [self.navigationController pushViewController:vc animated:YES];

}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAUserLocation class]]) {
        return nil;
    }
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
        CustomAnnotationView *annotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        // 设置为NO，用以调用自定义的calloutView
        annotationView.canShowCallout = NO;
        annotationView.selected = YES;
        // 设置中心点偏移，使得标注底部中间点成为经纬度对应点
        annotationView.centerOffset = CGPointMake(0, -18);
        return annotationView;
    }
    return nil;
}

@end
